package com.itfreer.data.sqlite;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.itfreer.data.general.ConnectionInfo;
import com.itfreer.data.general.Field;
import com.itfreer.data.general.GlobalDataType;
import com.itfreer.data.general.GlobalParameter;
import com.itfreer.data.general.IQueryMap;
import com.itfreer.data.general.ITable;
import com.itfreer.data.general.ITableInfo;
import com.itfreer.data.general.IUpdateMap;
import com.itfreer.data.general.IWorkspace;
import com.itfreer.data.general.OrderByType;
import com.itfreer.data.general.QueryMap;
import com.itfreer.data.general.RowBase;
import com.itfreer.data.general.TableType;
import com.itfreer.data.general.WherePara;
import com.itfreer.data.general.WorkspaceType;
import com.itfreer.utils.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

/**
 * 类功能说明 定义基于ado的数据库工作空间访问类
 */
public abstract class DatabaseWorkspaceBase implements IWorkspace {

	protected ConnectionInfo info;
	protected Context context;

	private HashMap<String, String> insertSqlCache = new HashMap<String, String>();
	private HashMap<String, String> updateSqlCache = new HashMap<String, String>();

	/**
	 * 构建工作空间
	 */
	public DatabaseWorkspaceBase(Context context, ConnectionInfo info) {
		this.info = info;
		this.context = context;
	}

	/**
	 * 替换SQL语句，用于数据库的差异化执行
	 */
	protected abstract String replaceSql(String sql);

	/**
	 * 获取得到一个表的自动增值SQL
	 */
	@Override
	public abstract String getAutoSql(ITable table, String fieldName);

	@Override
	public WorkspaceType getWorkspaceType() {
		return WorkspaceType.Sqlite;
	}

	@Override
	public String getDatabase() {
		return info.getDatabase();
	}

	@Override
	public String getUserID() {
		return info.getUserID();
	}

	@Override
	public String getPassword() {
		return info.getPassword();
	}

	@Override
	public int getVersion() {
		return info.getVersion();
	}

	@Override
	public String getConnectionString() {
		return info.getConnectionStr();
	}

	@Override
	public void startEditing() {

		TransactionsBlock.StartTransactions();
	}

	@Override
	public void stopEditing(boolean saveEdits) {

		TransactionsBlock.StopTransactions(context, info, saveEdits);
	}

	@Override
	public boolean isBeingEdited() {

		return TransactionsBlock.HasNextTransactions();
	}

	/**
	 * 执行SQL语句返回查询结果object
	 * 
	 * @param sqlString
	 * @param para
	 * @return
	 */
	@Override
	public Object getExecuteScalar(String sqlString, List<GlobalParameter> para) {
		SQLiteDatabase database = TransactionsBlock.GetDatabase(context, info);
		try {
			sqlString = replaceSql(sqlString);
			String[] source = ParameterHelper.GetStrings(para);
			Cursor cursor = database.rawQuery(sqlString, source);
            Object result = null;
			if(cursor.moveToNext()){
                result =  cursor.getString(0);
			}
            cursor.close();
            return result;
		} catch (Exception e) {
//			LogUtils.e(e.getMessage());
			throw e;
		} finally {
			TransactionsBlock.RefreshDatabase(context, info, database);
		}
	}

	/**
	 * 执行SQL语句返回查询结果object
	 * 
	 * @param queryMap
	 * @return
	 */
	@Override
	public Object getExecuteScalar(ITable pTable, IQueryMap queryMap) {
		String sql = null;
		if (queryMap == null) {
			sql = "select " + pTable.getSelectFields(false) + " from "
					+ pTable.getTableName();
			return getExecuteScalar(sql, GlobalParameter.Empty);
		} else {
			WherePara para = queryMap.getSql(pTable, false);
			return getExecuteScalar(para.sql, para.whereParas);
		}
	}

	/**
	 * 获取实体类，根据查询信息
	 * 
	 * @param queryMap
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@Override
	public <T extends RowBase> T getEntity(Class<T> c, ITable pTable, IQueryMap queryMap) {
		T entity = null;
        String sql = null;
        String[] paras = null;
        if (queryMap == null) {
            sql = "select " + pTable.getSelectFields(false) + " from "
                    + pTable.getTableName();
        } else {
            WherePara para = queryMap.getSql(pTable, true);
            paras = ParameterHelper.GetStrings(para.whereParas);
            sql = para.sql;
        }

		SQLiteDatabase database = TransactionsBlock.GetDatabase(context, info);
		try {
            sql = replaceSql(sql);
			Cursor cursor = database.rawQuery(sql, paras);
			if(cursor.moveToNext()){
                entity = getCursorEntity(c, cursor, pTable);
			}
            cursor.close();
            return entity;
		} catch (Exception e) {
//			LogUtils.e(e.getMessage());
			throw new RuntimeException(e);
		} finally {
			TransactionsBlock.RefreshDatabase(context, info, database);
		}
	}

    /**
     * 获取实体类，根据Cursor
     * @param c
     * @param cursor
     * @param pTable
     * @param <T>
     * @return
     */
    private <T extends RowBase> T getCursorEntity(Class<T> c, Cursor cursor, ITable pTable){
        try {
            T entity = c.newInstance();
            int count = cursor.getColumnCount();
            for(int i=0;i<count;i++){
                String columnName = cursor.getColumnName(i);
                Field field =  pTable.getField(columnName);
                if(field.getDataType() == GlobalDataType.Boolean){
                    entity.setValue(columnName, cursor.getInt(i));
                } else if(field.getDataType() == GlobalDataType.Char){
                    entity.setValue(columnName, cursor.getString(i));
                } else if(field.getDataType() == GlobalDataType.String){
                    entity.setValue(columnName, cursor.getString(i));
                } else if(field.getDataType() == GlobalDataType.Text){
                    entity.setValue(columnName, cursor.getString(i));
                } else if(field.getDataType() == GlobalDataType.Date){
                    entity.setValue(columnName, cursor.getString(i));
                } else if(field.getDataType() == GlobalDataType.DateTime){
                    entity.setValue(columnName, cursor.getString(i));
                } else if(field.getDataType() == GlobalDataType.Decimal){
                    entity.setValue(columnName, cursor.getDouble(i));
                } else if(field.getDataType() == GlobalDataType.Double){
                    entity.setValue(columnName, cursor.getDouble(i));
                } else if(field.getDataType() == GlobalDataType.Single){
                    entity.setValue(columnName, cursor.getFloat(i));
                } else if(field.getDataType() == GlobalDataType.Int16){
                    entity.setValue(columnName, cursor.getInt(i));
                } else if(field.getDataType() == GlobalDataType.Int32){
                    entity.setValue(columnName, cursor.getInt(i));
                } else if(field.getDataType() == GlobalDataType.Int64){
                    entity.setValue(columnName, cursor.getInt(i));
                } else if(field.getDataType() == GlobalDataType.UInt16){
                    entity.setValue(columnName, cursor.getInt(i));
                } else if(field.getDataType() == GlobalDataType.UInt32){
                    entity.setValue(columnName, cursor.getInt(i));
                } else if(field.getDataType() == GlobalDataType.UInt64){
                    entity.setValue(columnName, cursor.getLong(i));
                } else if(field.getDataType() == GlobalDataType.ByteArray){
                    entity.setValue(columnName, cursor.getBlob(i));
                } else if(field.getDataType() == GlobalDataType.NoDefault){
                    throw new RuntimeException("未知数据类型！");
                }
            }
            return entity;
        } catch (Exception e) {
            return null;
        }
    }

	/**
	 * 执行SQL语句返回查询结果List<RowBase>
	 * 
	 * @param queryMap
	 * @return
	 */
	@Override
	public <T extends RowBase> List<T> getEntityList(Class<T> c, ITable pTable,
			IQueryMap queryMap) {
        String sql = null;
        String[] paras = null;
        if (queryMap == null) {
            sql = "select " + pTable.getSelectFields(false) + " from "
                    + pTable.getTableName();
        } else {
            WherePara para = queryMap.getSql(pTable, true);
            paras = ParameterHelper.GetStrings(para.whereParas);
            sql = para.sql;
        }

        SQLiteDatabase database = TransactionsBlock.GetDatabase(context, info);
        try {
            sql = replaceSql(sql);
            Cursor cursor = database.rawQuery(sql, paras);
            List<T> list = new ArrayList<T>();
            while (cursor.moveToNext()){
                T entity = getCursorEntity(c, cursor, pTable);
                list.add(entity);
            }
            cursor.close();
            return list;
        } catch (Exception e) {
//            LogUtils.e(e.getMessage());
            throw new RuntimeException(e);
        } finally {
            TransactionsBlock.RefreshDatabase(context, info, database);
        }
	}

	/**
	 * 分页查询
	 * @return
	 */
	@Override
	public <T extends RowBase> List<T> pageSelect(Class<T> c, ITable pTable, IQueryMap queryMap) {
        String sql = null;
        String[] paras = null;
        if (queryMap == null) {
            sql = "select " + pTable.getSelectFields(false) + " from "
                    + pTable.getTableName();
        } else {
            WherePara para = queryMap.getSql(pTable, true);
            paras = ParameterHelper.GetStrings(para.whereParas);
            sql = para.sql;
        }

        SQLiteDatabase database = TransactionsBlock.GetDatabase(context, info);
        try {
            sql = replaceSql(sql);
            Cursor cursor = database.rawQuery(sql, paras);
            int start = 0;
            int end = 24;
            if(queryMap!=null){
                if(queryMap.getPageIndex() <=1){
                    start = 0;
                    end = queryMap.getPageSize() - 1;
                }else{
                    start = (queryMap.getPageIndex() - 1) * queryMap.getPageSize();
                    end = queryMap.getPageIndex() * queryMap.getPageSize() - 1;
                }
            }

            List<T> list = new ArrayList<T>();
            if(cursor.getCount()>=start){
                cursor.move(start);
                T entity = getCursorEntity(c, cursor, pTable);
                list.add(entity);
                for(int i=start+1;i<=end;i++){
                    if (cursor.moveToNext()){
                        entity = getCursorEntity(c, cursor, pTable);
                        list.add(entity);
                    }
                }
            }
            cursor.close();
            return list;
        } catch (Exception e) {
//            LogUtils.e(e.getMessage());
            throw new RuntimeException(e);
        } finally {
            TransactionsBlock.RefreshDatabase(context, info, database);
        }
	}

	/**
	 * 获取某列的最大值
	 * 
	 * @param fieldName
	 * @param where
	 * @return
	 */
	@Override
	public long getSpecFieldMaxValue(ITable pTable, String fieldName, HashMap<String, Object> where) {
		// 定义默认返回值
		long result = -1;
		// 组织获取最大值SQL
		IQueryMap queryMap = new QueryMap();
		queryMap.setSelectFields("max(" + fieldName + ") as MAXFIELDNAME");
		if(where!=null){
			queryMap.getWhereMap().putAll(where);
		}

        Object strResult = getExecuteScalar(pTable, queryMap);
        if(strResult!=null && strResult != ""){
            result = Long.parseLong(strResult.toString());
            return result;
        } else {
            return result;
        }
	}

	/**
	 * 获取某列的最小值
	 * 
	 * @param fieldName
	 * @param where
	 * @return
	 */
	@Override
	public long getSpecFieldMinValue(ITable pTable, String fieldName, HashMap<String, Object> where) {
		// 定义默认返回值
		long result = -1;

		// 组织获取最大值SQL
		IQueryMap queryMap = new QueryMap();
		queryMap.setSelectFields("min(" + fieldName + ") as MINFIELDNAME");
		if(where!=null){
			queryMap.getWhereMap().putAll(where);
		}

        Object strResult = getExecuteScalar(pTable, queryMap);
        if(strResult!=null && strResult != ""){
            result = Long.parseLong(strResult.toString());
            return result;
        } else {
            return result;
        }
	}

	/**
	 * 获取下一个要素，如果没有返回null
	 * 
	 * @param t
	 * @param byFieldName
	 * @param orderByType
	 * @param addCaptionField
	 * @return
	 */
	@Override
	public <T extends RowBase> T getNextEntity(Class<T> c, ITable pTable,
			RowBase t, String byFieldName, HashMap<String, Object> whereMap,
			OrderByType orderByType, boolean addCaptionField) {
		if (t == null || StringUtils.IsNullOrEmpty(byFieldName))
			return null;

		IQueryMap queryMap = new QueryMap();
		queryMap.setAddCaptionField(addCaptionField);
		Object value = t.getValue(GlobalDataType.String, byFieldName);
		
		switch (orderByType) {
		case ASC:
			queryMap.getWhereMap().put(byFieldName + ":>", value);
			queryMap.getOrderByMap().put(byFieldName, 0);
			break;
		case DESC:
			queryMap.getWhereMap().put(byFieldName + ":<", value);
			queryMap.getOrderByMap().put(byFieldName, 1);
			break;
		}

		if(whereMap!=null && whereMap.size()>0){
			queryMap.getWhereMap().putAll(whereMap);
		}
		return getEntity(c, pTable, queryMap);
	}

	/**
	 * 获取上一个要素，如果没有返回null
	 * 
	 * @param t
	 * @param byFieldName
	 * @param orderByType
	 * @param addCaptionField
	 * @return
	 */
	@Override
	public <T extends RowBase> T getPerEntity(Class<T> c, ITable pTable,
			RowBase t, String byFieldName, HashMap<String, Object> whereMap,
			OrderByType orderByType, boolean addCaptionField) {
		if (t == null || StringUtils.IsNullOrEmpty(byFieldName))
			return null;

		Object value = t.getValue(GlobalDataType.String, byFieldName);
		IQueryMap queryMap = new QueryMap();
		queryMap.setAddCaptionField(addCaptionField);
		switch (orderByType) {
		case ASC:
			queryMap.getWhereMap().put(byFieldName + ":<", value);
			queryMap.getOrderByMap().put(byFieldName, 1);
			break;
		case DESC:
			queryMap.getWhereMap().put(byFieldName + ":>", value);
			queryMap.getOrderByMap().put(byFieldName, 0);
			break;
		}
		
		if(whereMap!=null && whereMap.size()>0){
			queryMap.getWhereMap().putAll(whereMap);
		}
		return getEntity(c, pTable, queryMap);
	}

	/**
	 * 保存对象
	 */
	@Override
	public void save(ITable pTable, RowBase entity) {
		if (entity == null)
			return;
		if (entity.getIsNew()) {
			optionGuid(pTable, entity);
			executeSql(insertSql(pTable), insertParameter(pTable, entity));
		} else {
			executeSql(updateSql(pTable), updateParameter(pTable, entity));
		}
	}

	/**
	 * 批量保存对象
	 */
	@Override
	public <T extends RowBase> void save(ITable pTable, List<T> entitys) {
		if (entitys == null)
			return;
		List<List<GlobalParameter>> insertParameter = new ArrayList<List<GlobalParameter>>();
		List<List<GlobalParameter>> updateParameter = new ArrayList<List<GlobalParameter>>();

		for (RowBase entity : entitys) {
			if (entity.getIsNew()) {
				optionGuid(pTable, entity);
				insertParameter.add(insertParameter(pTable, entity));
			} else {
				updateParameter.add(updateParameter(pTable, entity));
			}
		}

		if (insertParameter != null && insertParameter.size() > 0) {
			executeSqls(insertSql(pTable), insertParameter);
		}

		if (updateParameter != null && updateParameter.size() > 0) {
			executeSqls(updateSql(pTable), updateParameter);
		}
	}

	/**
	 * 插入对象
	 */
	@Override
	public void insert(ITable pTable, RowBase entity) {
		if (entity == null)
			return;
		optionGuid(pTable, entity);
		executeSql(insertSql(pTable), insertParameter(pTable, entity));
	}

	/**
	 * 插入对象
	 */
	@Override
	public <T extends RowBase> void insert(ITable pTable, List<T> entitys) {
		if (entitys == null)
			return;
		List<List<GlobalParameter>> insertParameter = new ArrayList<List<GlobalParameter>>();

		for (RowBase entity : entitys) {
			optionGuid(pTable, entity);
			insertParameter.add(insertParameter(pTable, entity));
		}

		if (insertParameter != null && insertParameter.size() > 0) {
			executeSqls(insertSql(pTable), insertParameter);
		}
	}

	/**
	 * 更新或添加行
	 * 
	 * @param entity
	 * @return
	 */
	@Override
	public void update(ITable pTable, RowBase entity) {
		if (entity == null)
			return;

		executeSql(updateSql(pTable), updateParameter(pTable, entity));
	}

	/**
	 * 更新或添加行
	 * @return
	 */
	@Override
	public <T extends RowBase> void update(ITable pTable, List<T> entitys) {
		if (entitys == null)
			return;

		List<List<GlobalParameter>> updateParameter = new ArrayList<List<GlobalParameter>>();

		for (RowBase entity : entitys) {
			updateParameter.add(updateParameter(pTable, entity));
		}

		if (updateParameter != null && updateParameter.size() > 0) {
			executeSqls(updateSql(pTable), updateParameter);
		}
	}

	/**
	 * 更新数据
	 */
	@Override
	public void update(ITable pTable, IUpdateMap updateMap) {
		if (updateMap == null)
			return;
		WherePara wherePara = updateMap.getSql(pTable);
		executeSql(wherePara.sql, wherePara.whereParas);
	}

	/**
	 * 删除表记录
	 */
	@Override
	public void delete(ITable pTable, IQueryMap queryMap) {
		String sql = "delete from " + pTable.getTableName();
		WherePara wherePara = queryMap.getSql(pTable, false);
		if (wherePara != null && !StringUtils.IsNullOrSpace(wherePara.whereString)) {
			sql += " where " + wherePara.whereString;
			executeSql(sql, wherePara.whereParas);
		} else {
			executeSql(sql, GlobalParameter.Empty);
		}
	}

	/**
	 * 执行SQL语句返回影响行数
	 * @param para
	 * @return
	 */
	@Override
	public int executeSql(String strSql, List<GlobalParameter> para) {
        SQLiteDatabase database = TransactionsBlock.GetDatabase(context, info);
        try {
            strSql = this.replaceSql(strSql);
            Object[] source = ParameterHelper.GetObjects(para);
            database.execSQL(strSql, source);
            return 1;
        } catch (Exception e) {
//            LogUtils.e(e.getMessage());
            throw e;
        } finally {
            TransactionsBlock.RefreshDatabase(context, info, database);
        }
	}

	/**
	 * 批量执行SQL
	 * 
	 * @param sql
	 * @param paras
	 */
	@Override
	public void executeSqls(String sql, List<List<GlobalParameter>> paras) {
		if(paras==null || paras.size()<=0){
            executeSql(sql, null);
        }

        for(List<GlobalParameter> para : paras){
            executeSql(sql, para);
        }
	}

	/**
	 * 处理GUID
	 * 
	 * @param pTable
	 * @param entity
	 */
	protected void optionGuid(ITable pTable, RowBase entity) {
		// 处理GUID值
		if (!StringUtils.IsNullOrSpace(pTable.getGUIDFieldName())) {
			Object obj = entity.getValue(pTable.getGUIDFieldName());
			if (obj == null || StringUtils.IsNullOrSpace(obj.toString())) {
				UUID guid = UUID.randomUUID();
				entity.setValue(pTable.getGUIDFieldName(), guid.toString());
			}
		}
	}

	/**
	 * 获取插入SQL语句
	 * 
	 * @param pTable
	 * @return
	 */
	protected String insertSql(ITable pTable) {
		String key = pTable.getMetadataTableName();
		if (insertSqlCache.containsKey(key)) {
			return insertSqlCache.get(key);
		}

		// 插入新行
		String sql = "";
		String fieldList = "";
		for (Field item : pTable.getFields()) {
			if (item.getIsAuto()) {
				fieldList += "[" + item.getFieldName() + "],";
				sql += getAutoSql(pTable, item.getFieldName()) + ",";
			} else {
				fieldList += "[" + item.getFieldName() + "],";
				sql += "@" + item.getFieldName() + ",";
			}
		}

		if (sql.length() > 0) {
			fieldList = fieldList.substring(0, fieldList.length() - 1);
			sql = sql.substring(0, sql.length() - 1);
			sql = "Insert into " + pTable.getTableName() + " (" + fieldList
					+ ") values (" + sql + ")";
		}
		insertSqlCache.put(key, sql);
		return sql;
	}

	/**
	 * 获取插入参数
	 * 
	 * @param pTable
	 * @param entity
	 * @return
	 */
	protected List<GlobalParameter> insertParameter(ITable pTable, RowBase entity) {
		// 插入新行
		List<GlobalParameter> whereParameter = new ArrayList<GlobalParameter>();
		Object obj = null;
		for (Field item : pTable.getFields()) {
			if (!item.getIsAuto()) {
				obj = entity.getValue(item.getDataType(), item.getFieldName());
				whereParameter.add(new GlobalParameter("@"
						+ item.getFieldName(), obj, null, item.getDataType()
						.toString()));
			}
		}
		return whereParameter;
	}

	/**
	 * 获取更新SQL语句
	 * 
	 * @param pTable
	 * @return
	 */
	protected String updateSql(ITable pTable) {
		String key = pTable.getMetadataTableName();
		if (updateSqlCache.containsKey(key)) {
			return updateSqlCache.get(key);
		}

		String sql = "";
		String whereString = getUpdateWhere(pTable);
		for (Field item : pTable.getFields()) {
			if (!item.getIsAuto() && !item.getReadOnly()) {
				sql += "[" + item.getFieldName() + "]=@" + item.getFieldName()
						+ ",";
			}
		}
		if (sql.length() > 0) {
			sql = sql.substring(0, sql.length() - 1);
			sql = "update " + pTable.getTableName() + " set " + sql + " where "
					+ whereString;
		}
		updateSqlCache.put(key, sql);
		return sql;
	}

	/**
	 * 获取更新条件
	 * 
	 * @param pTable
	 * @return
	 */
	public static String getUpdateWhere(ITable pTable) {
		String whereString = "";
		// 根据GUID更新
		String guidField = pTable.getGUIDFieldName();
		if (!StringUtils.IsNullOrSpace(guidField)) {
			whereString += "[" + guidField + "]=@" + guidField;
		} else {
			// 根据主键进行更新
			Field[] keys = pTable.getKeyNoAutoFields();
			if (keys != null && keys.length > 0) {
				for (Field item : keys) {
					whereString += "[" + item.getFieldName() + "]=@"
							+ item.getFieldName();
				}
			} else {
				// 根据自动增值列更新数据
				Field[] autoFields = pTable.getAutoFields();
				if (autoFields != null && autoFields.length > 0) {
					whereString += "[" + autoFields[0].getFieldName() + "]=@"
							+ autoFields[0].getFieldName();
				} else {
					throw new RuntimeException("无法更新当前数据！原因：表"
							+ pTable.getTableName() + "没有主键！");
				}
			}
		}
		return whereString;
	}

	/**
	 * 获取更新条件
	 * 
	 * @param entity
	 * @return
	 */
	protected List<GlobalParameter> updateParameter(ITable pTable, RowBase entity) {

		List<GlobalParameter> whereParameters = getUpdateWhereParameter(pTable,
				entity);
		Object obj = null;
		List<GlobalParameter> setParameter = new ArrayList<GlobalParameter>();
		for (Field item : pTable.getFields()) {
			if (!item.getIsAuto() && !item.getReadOnly()) {
				obj = entity.getValue(item.getDataType(), item.getFieldName());
				setParameter.add(new GlobalParameter("@" + item.getFieldName(),
						obj, null, item.getDataType().toString()));
			}
		}
		setParameter.addAll(whereParameters);
		return whereParameters;
	}

	/**
	 * 获取更新条件的参数
	 * 
	 * @param pTable
	 * @param entity
	 * @return
	 */
	public static List<GlobalParameter> getUpdateWhereParameter(ITable pTable,
			RowBase entity) {
		List<GlobalParameter> whereParameters = new ArrayList<GlobalParameter>();
		Object obj;
		// 根据GUID更新
		String guidField = pTable.getGUIDFieldName();
		if (!StringUtils.IsNullOrSpace(guidField)) {
			obj = entity.getValue(guidField);
			whereParameters.add(new GlobalParameter("@" + guidField, obj, null,
					"String"));
		} else {
			// 根据主键进行更新
			Field[] keys = pTable.getKeyNoAutoFields();
			if (keys != null && keys.length > 0) {
				for (Field item : keys) {
					obj = entity.getValue(item.getFieldName());
					if (obj == null)
						throw new RuntimeException("数据更新失败！原因：主键["
								+ item.getFieldName() + "]取值错误！");

					whereParameters.add(new GlobalParameter("@"
							+ item.getFieldName(), obj, null, item
							.getDataType().toString()));
				}
			} else {
				// 根据自动增值列更新数据
				Field[] autoFields = pTable.getAutoFields();
				if (autoFields != null && autoFields.length > 0) {
					obj = entity.getValue(autoFields[0].getFieldName());
					if (obj == null)
						throw new RuntimeException("数据更新失败！原因：自动增值["
								+ autoFields[0].getFieldName() + "]取值错误！");

					whereParameters.add(new GlobalParameter("@"
							+ autoFields[0].getFieldName(), obj, null,
							autoFields[0].getDataType().toString()));
				}
			}
		}
		return whereParameters;
	}

	@Override
	public abstract boolean fieldExist(String name, String fieldName);

	@Override
	public abstract boolean objectExist(String objName);

	@Override
	public abstract TableType getObjectType(String objName);

	@Override
	public abstract void deleteObject(TableType tableType, String objName);

	@Override
	public abstract void rename(String oldTableName, String newTableName);

	@Override
	public abstract void createTable(ITableInfo tableInfo, String tableName);

	@Override
	public abstract void updateTable(ITableInfo tableInfo, String tableName);

	@Override
	public abstract void createOrUpdateView(String viewName, String selectSql,
			boolean isStatic);

	/**
	 * 关闭对象
	 */
	@Override
	public void close() {
        SQLiteDatabasePool.getInstance(context, info, true).refreshSQLiteDatabase();
	}
}